<template>
     <div  class="search-container">
        <form action="/"  class="search-form">
            <van-search
                v-model="searchText"
                show-action
                placeholder="请输入搜索关键词"
                @search="onSearch"
                @cancel="onCancel"
                @focus="isResultShow=false"
            />
            </form>

            <!-- 搜索结果 -->  
            <search-result v-if="isResultShow" :searchText="searchText"></search-result>  
                 
             <!-- 搜索建议 -->  
            <search-suggestion v-else-if="searchText" :searchText="searchText" @SuggestClick="onSearch"></search-suggestion>  

             <!--搜索历史-->
             <search-history  :search-his="searchHis"  @reSearch="onSearch" v-else></search-history>
          

     </div>
</template>

<script>
import { ref, onMounted, toRefs ,reactive,watch} from 'vue';
import SearchHistory from "./components/search-history.vue"
import SearchSuggestion from "./components/search-suggestion.vue"
import SearchResult from "./components/search-result.vue"
import {setItem,getItem} from "../../utils/storage"


function useSearch(state,searchText)
{
    const onSearch=(value)=>{
        state.isResultShow=true;
        searchText.value=value;

        const idx=state.searchHis.indexOf(value);
        if(idx!==-1)
        {

            state.searchHis.splice(idx,1);
        }
        state.searchHis.unshift(value);

        console.log(state.searchHis);
        console.log("on Search",value);


    }

    return { onSearch}
}
function useCancel()
{
    const onCancel=()=>{
        console.log("onCancel","取消");
    }
    return {onCancel}
}



export default {
    //组件使用项目  
    //props: { article:{ type:Object,required:true } },
    //使用组件 
    components:{
        SearchHistory,
        SearchSuggestion,
        SearchResult,
     },
    setup() {
        const searchText = ref('');
        const state =reactive({
            isResultShow:false,
            searchHis: getItem("TOUTIAO_SEARCG")|| []
        })
        watch(state.searchHis,function(newValue,oldValue){
           // console.log("watch searchHis",newValue);
           setItem("TOUTIAO_SEARCG",newValue);


            
        },{immediate:true})
        return {   
                      
            searchText,
            ...toRefs(state),
            ...useSearch(state,searchText),
            ...useCancel(),
        }
     }
};
</script>
<style>

     .search-container .van-search__action {
     color: blue;
    }

    .search-container .search-form
    {
        position: fixed;
        top:0;
        left: 0;
        right: 0;
        z-index: 2;
    }

</style>